package com.gyd.utils;





import com.gyd.marte.InitialActivity;

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;

public class PosicionGPS implements Runnable{

	TextView latitud;
	TextView longitud;
	InitialActivity activity;
	LocationManager mLocationManager;
	Location mLocation;
	MyLocationListener mLocationListener;
	Location actualposicion = null;
	Thread thread;
	
	public PosicionGPS(InitialActivity activity, TextView latitud,TextView longitud){
		this.latitud=latitud;
		this.longitud=longitud;
		this.activity=activity;
		thread = new Thread(this);
		
	}
	public void resume(){
		thread.resume();
	}
	public void stop(){
		thread.stop();
	}
	public void start(){
		thread.start();
	}
	
	@Override
	public void run() {
		mLocationManager = (LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);

		if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {			
			Looper.prepare();
			mLocationListener = new MyLocationListener();
			mLocationManager.requestLocationUpdates(
	                LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
			Looper.loop(); 
			Looper.myLooper().quit(); 
		}
    }
    private void setCurrentLocation(Location loc) {
    	actualposicion = loc;
    }
	   private Handler handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				
				mLocationManager.removeUpdates(mLocationListener);
		    	if (actualposicion!=null) {
		    		latitud.setText(Double.toString(actualposicion.getLatitude()));
		    		longitud.setText(Double.toString(actualposicion.getLongitude()));
		    	}
			}
		};
	    private class MyLocationListener implements LocationListener 
	    {
	        @Override
	        public void onLocationChanged(Location loc) {
	            if (loc != null) {
	                Toast.makeText(activity.getBaseContext(), 
	                		activity.getResources().getString(Constants.GPS_SIGNAL_FOUND), 
	                    Toast.LENGTH_LONG).show();
	                setCurrentLocation(loc);
	                handler.sendEmptyMessage(0);
	            }
	        }

	        @Override
	        public void onProviderDisabled(String provider) {
	            // TODO Auto-generated method stub
	        }

	        @Override
	        public void onProviderEnabled(String provider) {
	            // TODO Auto-generated method stub
	        }

	        @Override
	        public void onStatusChanged(String provider, int status, 
	            Bundle extras) {
	            // TODO Auto-generated method stub
	        }
	    } 
}
